package com.scm.erp.framework.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;


/**
 * 配置Security表单认证
 * */
@EnableWebSecurity
public class webSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private MyUserDetailsService myUserDetailsService;
    @Resource
    private AuthenticationSuccessHandler successHandler;

    @Resource
    private AuthenticationFailureHandler failureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/refreshJson").permitAll()
                .antMatchers("/loginAction").permitAll()
                .antMatchers("/submitLogin").permitAll()
                .antMatchers("/admin").fullyAuthenticated()
                .and().formLogin()

                .loginProcessingUrl("/submitLogin")
                .failureHandler(failureHandler)
                .successHandler(successHandler)
                .and().cors()
                .and().csrf().disable();


//        http.formLogin()
//                .usernameParameter("username")
//                .passwordParameter("password")
//                .loginProcessingUrl("/submitLogin")
//                .successForwardUrl("/loginAction")
//                .loginPage("/loginAction")
//                .failureHandler(FailureHandler)
//                .successHandler(SuccessHandler)
//                .and().cors()
//                .and().csrf().disable();
//               ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).withUser("ss").password("ss").authorities("ssaa");
        auth.userDetailsService(myUserDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**","/js/**","/images/**");
    }
}
